<?
Module::Init('system:structure');
BDS::Init();
$filter = array();
if(isset($params['code']) && !isset($params['block_id'])){
    $block = BDSBlocks::GetByCode($params['code']);
    if($block){
        $filter['block_id'] = $block['id'];
    }
}else{
    $filter['block_id'] = $params['block_id'];
}
$list = BDSSections::GetList($filter);
foreach($list as $i => $section){
    $fields = BDSFields::GetList(array('block_id' => $section['block_id'], 'relation' => 'S'));
    $f = array();
    foreach($fields as $j => $field){
        $f[$field['code']] = $field;
        $v = BDSFieldValues::GetList(array('field_id' => $field['id'], 'parent_id' => $section['id'], 'relation' => 'S'));
        $f[$field['code']]['value'] = $v[0]['value'];
    }
    $list[$i]['fields'] = $f;
}
$result = array('sections' => Tree($list, 'id', 'section_id', 'sections'));

function listTheme($data, $ul_class = "", $li_class = "", $useLink = false, $href = "", $level = 0){
    $str = "";
    foreach($data as $item){
        if($useLink){
            $href = $item['fields']['link']['value'];
            $selected = preg_match("#$href#", $_SERVER['REQUEST_URI']) ? "selected" : ""; 
        }else{
            $selected = "";
        }
        $str .= "<li class=\"$li_class $selected\">";
        if($useLink){
            $str .= "<a href=\"$href\">".$item['title']."</a>";
        }else{
            $str .= "<span>".$item['title']."</span>";
        }
        if(!empty($item['sections'])){
            $str .= listTheme($item['sections'], $ul_class, $li_class, $useLink, $href, $level+1);
        }
        $str .= "</li>";
    }
    return "<ul class=\"$ul_class level-$level\">".$str."</ul>";
}